|
1
|
|
|
import {chat, auth} from '@googleapis/chat'; |
|
2
|
|
|
import {GaxiosResponse} from 'gaxios/build/src/common'; |
|
3
|
|
|
|
|
4
|
|
|
/** |
|
5
|
|
|
* Create google api credentials |
|
6
|
|
|
* |
|
7
|
|
|
* @returns {object} google.chat |
|
8
|
|
|
*/ |
|
9
|
|
|
function gAuth() { |
|
10
|
|
|
// Use default credentials (service account) |
|
11
|
|
|
const credentials = new auth.GoogleAuth({ |
|
12
|
|
|
// keyFile: path.join(__dirname, '../../tests/creds.json'), |
|
13
|
|
|
scopes: ['https://www.googleapis.com/auth/chat.bot'], |
|
14
|
|
|
}); |
|
15
|
|
|
|
|
16
|
|
|
return chat({ |
|
17
|
|
|
version: 'v1', |
|
18
|
|
|
auth: credentials, |
|
19
|
|
|
}); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Call Google API using default credentials (service account) |
|
24
|
|
|
* |
|
25
|
|
|
* @param {string} action - request action(create,update,get,delete) |
|
26
|
|
|
* @param {object} request - request body |
|
27
|
|
|
* @returns {Promise<GaxiosResponse | {status: number, statusText: string, data: object}>} Response from google api |
|
28
|
|
|
*/ |
|
29
|
|
|
export async function callMessageApi( |
|
30
|
|
|
action: string, request: object): Promise<GaxiosResponse | {status: number, statusText: string, data: object}> { |
|
31
|
|
|
const chatApi = gAuth(); |
|
32
|
|
|
let response; |
|
33
|
|
|
|
|
34
|
|
|
try { |
|
35
|
|
|
if (action === 'create') { |
|
36
|
|
|
response = await chatApi.spaces.messages.create(request); |
|
37
|
|
|
} else if (action === 'update') { |
|
38
|
|
|
response = await chatApi.spaces.messages.update(request); |
|
39
|
|
|
} else if (action === 'get') { |
|
40
|
|
|
response = await chatApi.spaces.messages.get(request); |
|
41
|
|
|
} |
|
42
|
|
|
} catch (error) { |
|
43
|
|
|
// @ts-ignore: all error should have this method |
|
44
|
|
|
const errorMessage = error.message ?? error.toString() ?? 'Unknown error'; |
|
45
|
|
|
console.error('Error:', action, JSON.stringify(request), response, errorMessage); |
|
46
|
|
|
response = {'status': 444, 'statusText': errorMessage, 'data': {}}; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
if (!response) { |
|
50
|
|
|
throw new Error('Empty response'); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
return response; |
|
54
|
|
|
} |
|
55
|
|
|
|